#include "HTTPRequest.h"
//#include <QDebug>

#include "NetworkAccessManager.h"



HTTPRequest::HTTPRequest(QObject *parent)
    :QObject(parent)
{
    connect(NetworkAccessManager::instance(), SIGNAL(finished(QNetworkReply*)), this, SLOT(onFinished(QNetworkReply*)));
    //    connect(NetworkAccessManager::instance(), &QNetworkAccessManager::finished, this, [=] {
    //        qDebug() << "!!!!!!!!!!!!!yeah";
    //    });
}

HTTPRequest::~HTTPRequest()
{

}

bool HTTPRequest::checkURL(QUrl url)
{
    if (!url.isValid())
    {
        qCritical() << "[!HTTPRequest]ERROR:Invalid URL:" << url;
        return false;
    }

    if (url.scheme() == "http" || url.scheme() == "https")
    {
        if(url.scheme() == "https")
        {
            QSslConfiguration config = m_NetWorkRequest.sslConfiguration();
            config.setPeerVerifyMode(QSslSocket::VerifyNone);
            config.setProtocol(QSsl::TlsV1SslV3);
            m_NetWorkRequest.setSslConfiguration(config);
        }
    }
    else
    {
        qCritical() << "[!HTTPRequest]ERROR:URL must start with 'http/https:':" << url.scheme();
        return false;
    }

    if (url.path().isEmpty())   //必须要有路径（哪怕是单个/）
    {
        qCritical() << "[!HTTPRequest]ERROR:URL has no path!";
        return false;
    }
    //url.host(), url.port(80)

    return true;
}

bool HTTPRequest::get(QUrl url)
{
    if(NetworkAccessManager::instance()->networkAccessible() != QNetworkAccessManager::Accessible)
        return false;

    if(!checkURL(url))
        return false;

    m_baHttpData.clear();
    m_NetWorkRequest.setUrl(url);
    /******************设置http的header***********************/
    // m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    // m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    // m_NetWorkRequest.setRawHeader("Content-Disposition","form-data;name='doc';filename='a.txt'");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentLengthHeader,post_data.length());
    m_NetWorkRequest.setRawHeader("User-Agent", "HTTPRequest by Leamus");

    qDebug() << "[HTTPRequest]Request Header:" << m_NetWorkRequest.rawHeaderList();

    m_pNetWorkReply = NetworkAccessManager::instance()->get(m_NetWorkRequest);//通过发送数据，返回值保存在reply指针里.
    connect(m_pNetWorkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT( onDownloadProgress(qint64 ,qint64)));//download文件时进度
    connect(m_pNetWorkReply, SIGNAL(readyRead()),this, SLOT(onReadyRead()));
    connect(m_pNetWorkReply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT( onReplyError(QNetworkReply::NetworkError)) );//出现错误时发送此信号;
    connect(m_pNetWorkReply, &QNetworkReply::sslErrors, this, &HTTPRequest::onReplySslErrors);
    connect(m_pNetWorkReply, &QNetworkReply::finished, this, [=]{
        qDebug() << "[HTTPRequest]m_pNetWorkReply finished";
        //onFinished(m_pNetWorkReply);
    });


    return true;
}

bool HTTPRequest::post(QUrl url, QByteArray baData)
{
    if(!checkURL(url))
        return false;

    m_baHttpData.clear();
    m_NetWorkRequest.setUrl(url);
    /******************设置http的header***********************/
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
    //m_NetWorkRequest.setRawHeader("Content-Disposition","form-data;name='doc';filename='a.txt'");
    //m_NetWorkRequest.setHeader(QNetworkRequest::ContentLengthHeader,post_data.length());
    //m_NetWorkRequest.setRawHeader("Accept","*/*");
    //m_NetWorkRequest.setRawHeader("Accept-Language","zh-CN,zh;q=0.9");
    //m_NetWorkRequest.setRawHeader("Content-Type","application/x-www-form-urlencoded");
    //m_NetWorkRequest.setRawHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
    //m_NetWorkRequest.setRawHeader("X-Requested-With:","XMLHttpRequest");
    //m_NetWorkRequest.setRawHeader("Referer","http://ip.taobao.com/ipSearch.html");
    m_NetWorkRequest.setRawHeader("User-Agent", "HTTPRequest by Leamus");

    qDebug() << "[HTTPRequest]Request Header:" << m_NetWorkRequest.rawHeaderList();

    m_pNetWorkReply = NetworkAccessManager::instance()->post(m_NetWorkRequest, baData);//通过发送数据，返回值保存在reply指针里.
    connect(m_pNetWorkReply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT( onDownloadProgress(qint64 ,qint64)));//download文件时进度
    connect(m_pNetWorkReply, SIGNAL(readyRead()),this, SLOT(onReadyRead()));
    connect(m_pNetWorkReply, SIGNAL(error(QNetworkReply::NetworkError)),this, SLOT( onReplyError(QNetworkReply::NetworkError)) );//出现错误时发送此信号;
    connect(m_pNetWorkReply, &QNetworkReply::sslErrors, this, &HTTPRequest::onReplySslErrors);
    connect(m_pNetWorkReply, &QNetworkReply::finished, this, [=]{
        qDebug() << "[HTTPRequest]m_pNetWorkReply finished";
    });


    return true;
}

void HTTPRequest::onReadyRead()
{
    if(QNetworkReply::NoError == m_pNetWorkReply->error())
    {
        qDebug() << "[HTTPRequest]onReadyRead: NoError";
        m_baHttpData.append(m_pNetWorkReply->readAll());
    }
    else
    {
        qCritical() << "[!HTTPRequest]onReadyRead ERROR:" << m_pNetWorkReply->error();
    }

    //qDebug() << httpData;
    qDebug() << "[HTTPDownload]sender:" << this->sender() << m_pNetWorkReply;
}


/***************响应结束**************************/
void HTTPRequest::onFinished(QNetworkReply *reply)
{
    //获取响应的信息，状态码为200表示正常
    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    //无错误返回
    if(QNetworkReply::NoError == reply->error() && 200 == status_code)
    {
        qDebug() << "[HTTPRequest]Request Over:" << status_code << reply->error();
        emit s_finished(reply->error(), status_code.toInt());

    }
    else
    {
        //处理错误
        qCritical() << "[HTTPRequest]Request ERROR:" << status_code << reply->error();
        emit s_finished(reply->error(), status_code.toInt());
    }

    if(m_pNetWorkReply == reply)
        qDebug() << "[HTTPRequest]m_pNetWorkReply == reply";


    reply->deleteLater();//要删除reply，但是不能在onFinished里直接delete，要调用deletelater;

    //m_pNetWorkReply = NULL;
}

void HTTPRequest::onDownloadProgress(qint64 a,qint64 b)
{
    //file.write(reply->readAll());
    qDebug() << "[HTTPRequest]onDownloadProgress:" << a << "/" << b;
}

void HTTPRequest::onReplyError(QNetworkReply::NetworkError e)
{
    qCritical() << "[!HTTPRequest]onReplyError:" << e;
}

void HTTPRequest::onReplySslErrors(const QList<QSslError> &errors)
{
    qCritical() << "[!HTTPRequest]onReplySslErrors:" << errors;
}
